/**
 * Created by hongwen on 2017/7/10.
 */
import callChannel from '../../../../api/config/channel/call-channel'
import multiChannel from '../../../../api/config/channel/multi-channel'
import * as globalTypes from '../../../../mutation-types'
// ==================电话客服技能组==========================
/**
 * 获取所有通话设置
 * @param {Object} data
 * @param {String} data.Account 账号id
 * @param {String} data.PBX pbx
 */
export const getAllNodesByPbxForSkill = ({commit, state, rootState, dispatch}, data) => {
  return callChannel.getAllNodesByPbx(data)
    .then(response => {
      if (response.success) {
      /**
       * IVR主页面加载时，从服务端取出当前账户所有的IVR节点信息，存放在缓存里：session.ivrMap.1.1.1.102
       * 数据按节点类型:节点信息列表存储，如：{"ivr_node_announcement":[{..},{..}]}
       */
        // 构建一个 key-value对象，key是Exten，value是节点对象
        let accountLines = response.data.ivr_line
        accountLines.forEach(function (item) {
          if (item.Exten) {
            item.DisplayName = item.Exten
          } else {
            item.DisplayName = '未配置线路'
            item.UpdateTime = ''
            item.DidNum = ''
          }
          if (item.Dialout) {
            item.TypeName = '外呼线路'
          } else {
            item.TypeName = '呼转线路'
          }
        })
        let soundList = response.data.ivr_sound
        let normalSound = []
        soundList.forEach(function (item) {
          if (item.SoundType === 'normal') {
            normalSound.push(item)
          }
        })
        response.data.normal_sound = normalSound
        // 此接口在kf调用时不会返回ivr_sip （新版暂时没有sip管理，暂时先注释此代码）。
        // let sips = response.data.ivr_sip
        // let users = response.data.account_user
        // users.forEach(function (user) {
        //   for (let s in sips) {
        //     if (sips[s].UserID && sips[s].UserID === user._id) {
        //       sips[s].UserExten = user.exten
        //       sips[s].UserName = user.displayName
        //     }
        //   }
        // })
        let systemNode = response.data.system
        if (systemNode) {
          let systemNodeItem = null
          for (let i = 0; i < systemNode.length; i++) {
            systemNodeItem = systemNode[i]
            if (systemNodeItem.Exten && systemNodeItem.Exten === '2') {
              // system node only dial job number node, as array
              response.data.ivr_node_system = [systemNodeItem]
              break
            }
          }
        }
        commit(globalTypes.SET_IVRMAP, {ivrMap: response, PBX: data.PBX})
        // 是否进行过 全部节点获取
        commit(globalTypes.IS_GET_ALL_IVRMAP)
        // commit(globalTypes.SET_IVRMAP, Object.assign(ivrMapData, response)
        return response
      }
    })
    .catch(() => {
      commit(globalTypes.SET_ERROR, 'message.default_tips')
    })
}
/**
 * 获取指定通话设置
 * @param {Object} data
 * @param {String} data.Account 账号id
 * @param {String} data.PBX pbx
 * @param {String} data.type 参数type
 */
export const getAssignNodesByPbx = ({commit, state, rootState, dispatch}, data) => {
  if (rootState.session && rootState.session.ivrMap && rootState.session.ivrMap[data.PBX] && rootState.session.ivrMap[data.PBX].data && rootState.session.ivrMap[data.PBX].data[data.type]) {
    return
  }
  commit(globalTypes.SET_SKILL_GROUP_LOADING, true)
  return callChannel.getAssignNodesByPbx(data)
    .then(response => {
      if (response.success) {
        commit(globalTypes.SET_ASSIGN_IVRMAP, {type: data.type, assign: response[data.type], PBX: data.PBX})
        commit(globalTypes.SET_SKILL_GROUP_LOADING, false)
        return response
      }
    })
    .catch(() => {
      commit(globalTypes.SET_ERROR, 'message.default_tips')
    })
}
/**
 * 查询技能组列表
 * @param {Object} data
 * @param {String} data.Account 账户id
 * @param {String} data.PBX pbx
 */
export const queryQueueForSkill = ({commit, state, rootState, dispatch}, data) => {
  return callChannel.queryQueue(data)
    .then(response => {
      if (response.success) {
        return response
      }
    })
    .catch(() => {
      commit(globalTypes.SET_ERROR, 'message.default_tips')
    })
}
/**
 * 添加/修改技能组
 * @param {Object} data
 * @param {String} data.Account 账户id
 * @param {String} data.PBX pbx
 * @param {String} data.action 'add' => 添加，'update' => 修改
 * @param {String} data.State 是否启用（没找到使用的地方，传'enable'）
 * @param {String} data.Type 类型，'normal'
 * @param {String} data.DisplayName 名称
 * @param {String} data.Strategy 'rrmemory'
 * @param {Boolean} data.SayExten 是否启用报工号
 * @param {Boolean} data.AgentExtenPoint 是否启用报工号后的提示音
 * @param {String} data.JoinEmpty 无空闲座席时立刻流转，'1' => 是，'0' => 否
 * @param {String|Number} data.SayQueuePosition 播报排队位置时间间隔，'0' => 不播报
 * @param {String} data.BussinessTypeId 来电弹屏，'business_${工单流程id}'，'callUrls_${来电弹屏id}'
 * @param {String} data.MusicClass 等待语音
 * @param {String} data.Music 进入技能组提示音
 * @param {String|Number} data.WaitTime 等待时长
 * @param {String|Number} data.Timeout 座席振铃时长
 * @param {String} data.ToPeerTypeWhenQueueEmpty 技能组为空时转向类型
 * @param {String} data.ToPeerWhenQueueEmpty 技能组为空时转向
 * @param {String} data.ToPeerTypeWhenWait 正在等待时转向类型
 * @param {String} data.ToPeerWhenWait 正在等待时转向
 * @param {String} data.ToPeerTypeWhenWaitTimeout 等待超时转向类型
 * @param {String} data.ToPeerWhenWaitTimeout 等待超时转向
 * @param {String} data.ToPeerTypeWhenHanguped 通话结束后转向类型
 * @param {String} data.ToPeerWhenHanguped 通话结束后转向
 * @param {String} data.MemberToken 座席分配，['${座席id}:${优先级}']
 * ---- 以下为修改时要另外提供的 ----
 * @param {String} [data._id] 技能组id
 * @param {String} [data.Exten] 技能组号
 */
export const updateQueueForSkill = ({commit, state, rootState, dispatch}, data) => {
  return callChannel.updateQueue(data)
    .then(response => {
      if (response.success) {
        return response
      }
    })
    .catch(() => {
      commit(globalTypes.SET_ERROR, 'message.default_tips')
    })
}
/**
 * 删除技能组
 * @param {Object} data
 * @param {*} data.* 与修改技能组传参相同
 */
export const deleteQueueForSkill = ({commit, state, rootState, dispatch}, data) => {
  return callChannel.deleteQueue(data)
    .then(response => {
      if (response.success) {
        return response
      }
    })
    .catch(() => {
      commit(globalTypes.SET_ERROR, 'message.default_tips')
    })
}
/**
 * 复制技能组
 * @param {Object} data
 * @param {*} data.* 与修改技能组传参相同
 */
export const cloneQueueForSkill = ({commit, state, rootState, dispatch}, data) => {
  return callChannel.cloneQueue(data)
    .then(response => {
      if (response.success) {
        return response
      }
    })
    .catch(() => {
      commit(globalTypes.SET_ERROR, 'message.default_tips')
    })
}
// ==================互联网渠道技能组==========================
/**
 * 技能组查询
 * @param {Object} data
 * @param {Number} [data.limit] 分页查询limit，默认10
 * @param {Number} [data.page] 分页查询page，默认1
 */
export const queryEmailQueueForSkill = ({commit, state, rootState, dispatch}, data) => {
  return multiChannel.queryEmailQueue(data)
    .then(response => {
      if (response.success) {
        return response
      }
    })
    .catch(() => {
      commit(globalTypes.SET_ERROR, 'message.default_tips')
    })
}
/**
 * 添加或更新
 * @param data._id 技能组id
 * @returns {*}
 */
export const addOrUpdateEmailQueueForSkill = ({commit, state, rootState, dispatch}, data) => {
  return multiChannel.addOrUpdateEmailQueue(data)
    .then(response => {
      if (response.success) {
        return response
      }
    })
    .catch(() => {
      commit(globalTypes.SET_ERROR, 'message.default_tips')
    })
}
/**
 * 获取空闲技能组号
 * @param data
 * @returns {*}
 */
export const getFreeQueueNoForSkill = ({commit, state, rootState, dispatch}, data) => {
  return multiChannel.getFreeQueueNo(data)
    .then(response => {
      if (response.success) {
        return response
      }
    })
    .catch(() => {
      commit(globalTypes.SET_ERROR, 'message.default_tips')
    })
}
/**
 * 删除技能组
 * @param data
 * @returns {*}
 */
export const deleteEmailQueueForSkill = ({commit, state, rootState, dispatch}, data) => {
  return multiChannel.deleteEmailQueue(data)
    .then(response => {
      if (response.success) {
        return response
      }
    })
    .catch(() => {
      commit(globalTypes.SET_ERROR, 'message.default_tips')
    })
}
/**
 * 根据id查询技能组
 * @param data._id 技能组id
 * @returns {*}
 */
export const queryEmailQueueByIdForSkill = ({commit, state, rootState, dispatch}, data) => {
  return multiChannel.queryEmailQueueById(data)
    .then(response => {
      if (response.success) {
        return response
      }
    })
    .catch(() => {
      commit(globalTypes.SET_ERROR, 'message.default_tips')
    })
}

// 查询工单技能组
export const queryBusinessQueue = ({commit, state, rootState, dispatch}, data) => {
  return multiChannel.queryBusinessQueue(data)
    .then(response => {
      if (response.success) {
        return response
      }
    })
    .catch(() => {
      commit(globalTypes.SET_ERROR, 'message.default_tips')
    })
}

// 增加修改工单技能组
export const updateBusinessQueue = ({commit, state, rootState, dispatch}, data) => {
  return multiChannel.updateBusinessQueue(data)
    .then(response => {
      if (response.success) {
        return response
      }
    })
    .catch(() => {
      commit(globalTypes.SET_ERROR, 'message.default_tips')
    })
}

// 删除工单技能组
export const deleteBusinessQueue = ({commit, state, rootState, dispatch}, data) => {
  return multiChannel.deleteBusinessQueue(data)
    .then(response => {
      if (response.success) {
        return response
      }
    })
    .catch(() => {
      commit(globalTypes.SET_ERROR, 'message.default_tips')
    })
}

/**
 * 根据id查询技能组
 * @param data._id 技能组id
 * @returns {*}
 */
export const queryBusinessQueueById = ({commit, state, rootState, dispatch}, data) => {
  return multiChannel.queryBusinessQueueById(data)
    .then(response => {
      if (response.success) {
        return response
      }
    })
    .catch(() => {
      commit(globalTypes.SET_ERROR, 'message.default_tips')
    })
}
